package com.aptech.oas.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.aptech.oas.model.Email;
import com.aptech.oas.util.SessionFactoryUtil;

public class EmailDaoImpl implements EmailDao {

	@Override
	public List<Email> selectAllEmails() {
		Session session=SessionFactoryUtil.get().openSession();
		Query q=session.createQuery("from Email");
		List<Email> emails=q.list();
		session.close();
		return emails;
	}

	@Override
	public Email selectEmailById(Long eid) {
		Session session=SessionFactoryUtil.get().openSession();
		Query q=session.createQuery("from Email e where e.eid= :id");
		q.setLong("id", eid);
		Email email=(Email)q.uniqueResult();
		session.close();
		return email;
	}

	@Override
	public void updateEmail(Email email) {
		Session session=SessionFactoryUtil.get().openSession();
		session.beginTransaction();
		session.update(email);
		session.getTransaction().commit();
		session.close();
		return;
	}

	@Override
	public List<Email> receiveEmail(String receiverWorkNo,Boolean status) {
		Session session=SessionFactoryUtil.get().openSession();
		Query q=session.createQuery("from Email e where e.receiver= ? and e.status= ?");
		q.setString(0, receiverWorkNo);
		q.setBoolean(1, status);
		List<Email> emails=q.list();
		session.close();
		return emails;
	}

	/**
	 * hql 的update 和delete操作，
	 * 都需要transaction.commit()才能与数据库同步，数据库才执行update、delete
	 */
	@Override
	public Integer deleteEmail(Long eid) {
		Session session=SessionFactoryUtil.get().openSession();
		session.beginTransaction();
		Query q =session.createQuery("delete Email e where e.eid= ?");
		q.setLong(0, eid);
		int result=q.executeUpdate();
		session.getTransaction().commit();
		return result;
	}

	

}
